package handler;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;

import javax.swing.JProgressBar;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import parser.CmmLexer;
import parser.CmmParser;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

import ir.*;
import ui.MainFrame;

//运行cmm文件处理类
public class CmmRunHandler {

	
	public String interpret(MainFrame editorFrame) {
		try {
			String sourcePath = editorFrame.getCurrentFile().getFile().getAbsolutePath();
			
			System.setOut(new PrintStream(new FileOutputStream("F:\\workspace\\cmmwithide\\out\\output.txt")));
			
			ANTLRInputStream input = new ANTLRInputStream(new FileInputStream(sourcePath));
			CmmLexer cl=new CmmLexer(input);
			CmmParser parser=new CmmParser(new CommonTokenStream(cl));
			ParseTree rule=parser.program();
			ParseTreeWalker walker=new ParseTreeWalker();
            IRProduceListener IR = new IRProduceListener();
			walker.walk(IR,rule);
            IRExecuter EX = new IRExecuter(IR.Code);
            boolean b = EX.excute();
            if(b==false){
            	Process process = Runtime.getRuntime().exec("cmd /k start out" + File.separator + "exec.bat " + sourcePath);
            	return null;
            }
            else{
            	String result = "";
                try{
                    BufferedReader br = new BufferedReader(new FileReader("F:\\workspace\\cmmwithide\\out\\output.txt"));//构造一个BufferedReader类来读取文件
                    String s = null;
                    while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                        result=result+s+"\n";
                    }
                    br.close();    
                }catch(Exception e){
                    e.printStackTrace();
                }
                
    			JProgressBar progressBar = editorFrame.getProgressBar();
    			progressBar.setStringPainted(true);  
    	        new Thread(){  
    	            public void run(){  
    	                progressBar.setValue(100);  
    	                 
    	                progressBar.setString("完成");  
    	            }  
    	        }.start(); 
    			return result;
            }
            
		} 
		catch (Exception e) {
			return e.getMessage();
		}
	}
	
	public String LexicalAnalysis(MainFrame editorFrame){
		try{
			//获得源文件的全路径
			String sourcePath = editorFrame.getCurrentFile().getFile().getAbsolutePath();
			String result = "";
			FileInputStream is = new FileInputStream(sourcePath);
			ANTLRInputStream input = new ANTLRInputStream(is);
			CmmLexer lexer = new CmmLexer(input);
			List list=lexer.getAllTokens();
			Iterator<CommonToken> iterator = list.iterator();
			while(iterator.hasNext()){
				CommonToken token = iterator.next();
				result = result + "Line "+token.getLine()+"   "+lexer.ruleNames[token.getType()-1]+"   "+token.getText()+"\n";
			}
			JProgressBar progressBar = editorFrame.getProgressBar();
			progressBar.setStringPainted(true);  
	        new Thread(){  
	            public void run(){  
	            	progressBar.setValue(100);  
	                 
	                progressBar.setString("完成");  
	            }  
	        }.start(); 
			return result;
		}catch(Exception e){
			return e.getMessage();
		}
	}
	
	public String SynaticalAnalysis(MainFrame editorFrame){
		try{
			//获得源文件的全路径
			String sourcePath = editorFrame.getCurrentFile().getFile().getAbsolutePath();
			String result = "";
			FileInputStream is = new FileInputStream(sourcePath);
			ANTLRInputStream input = new ANTLRInputStream(is);
			CmmLexer lexer = new CmmLexer(input);
			CommonTokenStream tokens = new CommonTokenStream(lexer);
			//List list=lexer.getAllTokens();
			CmmParser parser = new CmmParser(tokens);
			ParseTree tree = parser.program();
			result = tree.toStringTree(parser);
			//parser.prog();
			//result = parser.visit();
			JProgressBar progressBar = editorFrame.getProgressBar();
			progressBar.setStringPainted(true);  
	        new Thread(){  
	            public void run(){  
	            	progressBar.setValue(100);  
	                progressBar.setString("完成");  
	            }  
	        }.start(); 
			return result;
		}catch(Exception e){
			return e.getMessage();
		}
	}
	public String irProduce(MainFrame editorFrame){
		try{
			//获得源文件的全路径
			String sourcePath = editorFrame.getCurrentFile().getFile().getAbsolutePath();
			String result = "";
			
			FileInputStream is = new FileInputStream(sourcePath);
			ANTLRInputStream input = new ANTLRInputStream(is);
			System.setOut(new PrintStream(new FileOutputStream("F:\\workspace\\cmmwithide\\out\\output1.txt")));
			System.setErr(new PrintStream(new FileOutputStream("F:\\workspace\\cmmwithide\\out\\output2.txt")));
			CmmLexer cl=new CmmLexer(input);
			CmmParser parser=new CmmParser(new CommonTokenStream(cl));
			ParseTree rule=parser.program();
			ParseTreeWalker walker=new ParseTreeWalker();
			IRProduceListener irListener = new IRProduceListener();
			
			
			walker.walk(irListener,rule);
			Iterator<IRLine> ir = irListener.Code.iterator();
			
			IRLine line;
			while(ir.hasNext()){
				line = ir.next();
				result = result + line.toString()+"\n";
			}
			if(result.equals("")){
				String result1 = "";
	            try{
	                BufferedReader br = new BufferedReader(new FileReader("F:\\workspace\\cmmwithide\\out\\output2.txt"));//构造一个BufferedReader类来读取文件
	                String s = null;
	                while((s = br.readLine())!=null){//使用readLine方法，一次读一行
	                    result1=result1+s+"\n";
	                }
	                br.close(); 
	                return result1;
	            }catch(Exception e){
	                e.printStackTrace();
	            }
			}
			else{
				System.out.println(result);
				String result2 = "";
	            try{
	                BufferedReader br = new BufferedReader(new FileReader("F:\\workspace\\cmmwithide\\out\\output1.txt"));//构造一个BufferedReader类来读取文件
	                String s = null;
	                while((s = br.readLine())!=null){//使用readLine方法，一次读一行
	                    result2=result2+s+"\n";
	                }
	                br.close(); 
	                return result2;
	            }catch(Exception e){
	                e.printStackTrace();
	            }
			}
			JProgressBar progressBar = editorFrame.getProgressBar();
			progressBar.setStringPainted(true);
			new Thread(){
				public void run(){
					progressBar.setValue(100);
					progressBar.setString("完成");
				}
			}.start();
			return result;
		}catch(Exception e){
			return e.getMessage();
		}
	}
}

